/**
 *
 */
package com.iknight.mgr.controller;

import com.github.pagehelper.PageInfo;
import com.iknight.mgr.api.MenuService;
import com.iknight.mgr.core.base.BaseController;
import com.iknight.mgr.core.constant.IkgConstantCode;
import com.iknight.mgr.core.jstree.JsTreeNode;
import com.iknight.mgr.core.jstree.NodeStatus;
import com.iknight.mgr.core.tree.MenuTreeNode;
import com.iknight.mgr.core.tree.TreeUtils;
import com.iknight.mgr.core.utils.IkgStringUtils;
import com.iknight.mgr.core.utils.IkgWebUtils;
import com.iknight.mgr.model.MenuModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author Jeryzym
 */
@RestController
@RequestMapping("/rest/menu")
@Api(protocols = "http", value = "用户菜单控制器")
public class MenuController implements BaseController<MenuModel> {

    private static Logger logger = LogManager.getLogger(MenuController.class);

    @Value("${enableRoot}")
    private boolean enableRoot;
    @Value("${rootName}")
    private String rootName;

    @Autowired
    private MenuService<MenuModel, String> menuService;

    public MenuModel format(Map<String, Object> params) {
        // TODO Auto-generated method stub
        // return null;
        MenuModel record = new MenuModel();
        record.setMenu_id(IkgStringUtils.ObjectToString(params.get("menu_id")));
        if (!IkgStringUtils.isNull(params.get("menu_name"))) {
            record.setMenu_name(IkgStringUtils.ObjectToString(params.get("menu_name")));
        }
        if (!IkgStringUtils.isNull(params.get("menu_code"))) {
            record.setMenu_code(IkgStringUtils.ObjectToString(params.get("menu_code")));
        }
        if (!IkgStringUtils.isNull(params.get("menu_uri"))) {
            record.setMenu_uri(IkgStringUtils.ObjectToString(params.get("menu_uri")));
        }

        if (!IkgStringUtils.isNull(params.get("template_uri"))) {
            record.setTemplate_uri(IkgStringUtils.ObjectToString(params.get("template_uri")));
        }

        if (!IkgStringUtils.isNull(params.get("script_uri"))) {
            record.setScript_uri(IkgStringUtils.ObjectToString(params.get("script_uri")));
        }

        if (!IkgStringUtils.isNull(params.get("p_menu_id"))) {
            record.setP_menu_id(IkgStringUtils.ObjectToString(params.get("p_menu_id")));
        }

        if (!IkgStringUtils.isNull(params.get("icon_cls"))) {
            record.setIcon_cls(IkgStringUtils.ObjectToString(params.get("icon_cls")));
        }

        if (params.get("edit_status") != null && params.get("edit_status").toString().equals("0")) {
            record.setEffective_date(IkgStringUtils.getCurrentDate("yyyy-MM-dd HH:mm"));
        }
        if (!IkgStringUtils.isNull(params.get("record_status"))) {
            record.setRecord_status(IkgStringUtils.ObjectToInt(params.get("record_status")));
        }
        if (!IkgStringUtils.isNull(params.get("expire_date"))) {
            record.setExpire_date(IkgStringUtils.ObjectToString(params.get("expire_date")));
        }
        record.setIsLeaf("1");//默认叶子节点
        record.setShow_order(IkgStringUtils.ObjectToInt(menuService.getNextShowOrder()));
        return record;
    }

    /**
     * saveOrUpdate
     */
    @PostMapping("/save")
    @ApiOperation(httpMethod = "post", notes = "系统菜单保存方法，传入菜单数据，经格式化后入库", value = "save")
    /*@RequiresPermissions("mgr.menu.save")
    @RequiresRoles("admin")*/
    public Object save(@RequestBody Map<String, Object> params, HttpServletRequest request,
                       HttpServletResponse response) {
        // TODO Auto-generated method stub
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        menuService.save(format(params));
        return IkgWebUtils.postIkgResponse(true, "保存成功!", IkgConstantCode.OPERSUCCESS);
    }


    @PostMapping("/delete")
    /*@RequiresPermissions("mgr.menu.delete")
    @RequiresRoles("admin")*/
    public Object delete(@RequestBody Map<String, Object> params, HttpServletRequest request,
                         HttpServletResponse response) {
        // TODO Auto-generated method stub
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        menuService.delete(IkgStringUtils.ObjectToString(params.get("menu_id")));
        return IkgWebUtils.postIkgResponse(true, "删除成功!", IkgConstantCode.OPERSUCCESS);
    }

    @PostMapping("/selectOne")
//	@RequiresPermissions("mgr.menu.selectone")
    public Object selectOne(@RequestBody Map<String, Object> params, HttpServletRequest request,
                            HttpServletResponse response) {
        // TODO Auto-generated method stub
        // return null;
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        MenuModel record = menuService.selectOne(IkgStringUtils.ObjectToString(params.get("menu_id")));
//        return IkgWebUtils.postMsg(record);
        return IkgWebUtils.postIkgResponse(true, "查询成功!", record);
    }

    @Deprecated
    @PostMapping("/selectAll")
//	@RequiresPermissions("mgr.menu.selectall")
    public Object selectAll(HttpServletRequest request, HttpServletResponse response) {
        List<MenuModel> menus = menuService.selectAll();
        List<MenuTreeNode> menusTree = new ArrayList<MenuTreeNode>();
        if (null == menus || menus.size() == 0) {
            return null;
        }
        Iterator<MenuModel> ita = menus.iterator();

        while (ita.hasNext()) {
            MenuModel record = ita.next();
            MenuTreeNode node = new MenuTreeNode();
            node.setId(record.getMenu_id());
            node.setText(record.getMenu_name());
            if (!IkgStringUtils.isNull(record.getP_menu_id())) {
                node.setPid(record.getP_menu_id());
            }
            if (!IkgStringUtils.isNull(record.getIcon_cls())) {
                node.setIcon(record.getIcon_cls());
            }
            if (!IkgStringUtils.isNull(record.getMenu_uri())) {
                node.setUrl(record.getMenu_uri());
            }
            menusTree.add(node);
        }
        List<MenuTreeNode> treeNodes = TreeUtils.getRootNode(menusTree);
        return JSONArray.fromObject(treeNodes);
    }

    @PostMapping("/changeMenuPid")
//	@RequiresPermissions("mgr.menu.cmp")
//	@RequiresRoles("admin")
    public Object changeMenuPid(@RequestBody Map<String, Object> params, HttpServletRequest request,
                                HttpServletResponse response) {
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        String menu_id = params.get("menu_id").toString();
        String p_menu_id = params.get("p_menu_id") == null ? "" : params.get("p_menu_id").toString();
        menuService.changeMenuPid(menu_id, p_menu_id);
        return IkgWebUtils.postIkgResponse(true, "变更父级节点数据成功!", IkgConstantCode.OPERSUCCESS);
    }

    public boolean isPKeyNotNull(Map<String, Object> params) {
        return params != null && params.get("menu_id") != null;
    }

    @PostMapping("/list")
//	@RequiresPermissions("mgr.menu.list")
    public Object selectByPage(@RequestBody Map<String, Object> params, HttpServletRequest request,
                               HttpServletResponse response) {
        // TODO Auto-generated method stub
        // return null;
        if (params == null) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        int pageIndex = IkgStringUtils.ObjectToInt(params.get("pageNumber"));
        int pageSize = IkgStringUtils.ObjectToInt(params.get("pageSize"));

        PageInfo<MenuModel> perms = menuService.selectPage(params, pageIndex, pageSize);
        return IkgWebUtils.postResult(perms.getTotal(), perms.getList());
    }

    @PostMapping("/getTreeNodes")
    public Object lazyLoadTree(@RequestBody Map<String, Object> params, HttpServletRequest request,
                               HttpServletResponse response) {
        String nodeId = IkgStringUtils.ObjectToString(params.get("nodeId"));
        if (nodeId.equals("#")) {
            nodeId = "";
        }
//        定义根节点
        JsTreeNode rootNode = new JsTreeNode();


        List<MenuModel> nodes = menuService.getTreeNode(nodeId);
        List<JsTreeNode> treeNodes = new ArrayList<>();

        if (enableRoot) {
            rootNode.setId(UUID.randomUUID().toString());
            rootNode.setText(rootName);
            rootNode.setParent("#");
            rootNode.setState(new NodeStatus(false, false, false, false));
            JSONObject rootAttr = new JSONObject();
            rootAttr.put("isRoot", true);
            rootNode.setAttributes(rootAttr);
            treeNodes.add(rootNode);
        }

        for (MenuModel node : nodes) {
            JsTreeNode jsTreeNode = new JsTreeNode();
            jsTreeNode.setId(node.getMenu_id());
            jsTreeNode.setText(node.getMenu_name());
            jsTreeNode.setIcon(node.getIcon_cls());
            JSONObject attr = new JSONObject();
            attr.put("templateUri", node.getTemplate_uri());

            jsTreeNode.setAttributes(attr);
            jsTreeNode.setState(new NodeStatus(false, false, false, false));

            if (IkgStringUtils.ObjectToString(node.getP_menu_id()).length() == 0) {
                if (enableRoot) {
                    jsTreeNode.setParent(rootNode.getId());
                } else {
                    jsTreeNode.setParent("#");
                }
            } else {
                jsTreeNode.setParent(node.getP_menu_id());
            }

            treeNodes.add(jsTreeNode);
        }
        return JSONArray.fromObject(treeNodes);
    }
}
